﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Management;
using System.Windows.Forms;
using System.Collections.Generic;
namespace taobaoSpider
{
    public static class GlobalFun
    {
        /// <summary>
        /// 写信息到磁盘中。。
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="append">true 追加  false:覆盖</param>
        /// <param name="content">写入的内容</param>
        public static void Write(string fileName,bool append,string content)
        {
           // fileName = System.Windows.Forms.Application.StartupPath + "\\" + fileName;
            StreamWriter sw = new StreamWriter(fileName,append,System.Text.Encoding.Default);
            sw.WriteLine(content);
            sw.Flush();
            sw.Close();
        }

        public static void PrintLog(string errPos, string errMsg)
        {
            string fileName = System.Windows.Forms.Application.StartupPath + "\\error.log";
            StreamWriter sw = new StreamWriter(fileName, true, System.Text.Encoding.Default);
            sw.WriteLine(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ":" + errPos + "--" + errMsg);
            sw.Flush();
            sw.Close();
        }

        public static void PrintExceptionLog(Exception ex)
        {
            PrintLog("---------------产生异常", "-----------------");
            PrintLog("Message --{0}", ex.Message);
            PrintLog("HelpLink --{0}", ex.HelpLink);
            PrintLog("Source --{0}", ex.Source);
            PrintLog("StackTrace --{0}", ex.StackTrace);
            PrintLog("TargetSite --{0}", ex.TargetSite.ToString());
            PrintLog("---------------异常结束", "-----------------");
        }

        /// <summary>
        /// 写错误日志，
        /// </summary>
        /// <param name="errPos">传入错误发生的位置</param>
        /// <param name="exMessage">异常信息</param>
        public static void WriteErrorLog(string errPos,string exMessage)
        {
            string fileName = System.Windows.Forms.Application.StartupPath + "\\error.log";
            string content = DateTime.Now.ToShortDateString() + "  " + DateTime.Now.ToLongTimeString() + "--" + errPos + "--" + exMessage;
            Write(fileName, true, content);
        }

        public static void WriteExceptionLog(string errPos, string exMessage)
        {
            string fileName = System.Windows.Forms.Application.StartupPath + "\\NetException.log";
            string content = DateTime.Now.ToShortDateString() + "  " + DateTime.Now.ToLongTimeString() + "--" + errPos + "--" + exMessage;
            Write(fileName, true, content);
        }

        public static ArrayList ReadFile(string fileName)
        {
            ArrayList list = new ArrayList();
            StreamReader sr = new StreamReader(fileName,System.Text.Encoding.Default);
            while (!sr.EndOfStream)
            {
                list.Add(sr.ReadLine());
            }
            sr.Close();
            return list;
        }

        public static void CloseComputerSystem()
        {
           // ConnectionOptions BootConn = new ConnectionOptions();
           // BootConn.Username = "";
           // BootConn.Password = "";
            //string computerName=ReadIniFile.IniReadValue("closeCoumpter", "computerName");
            string computerName=System.Net.Dns.GetHostName();
            ManagementScope ms = new ManagementScope("\\\\"+computerName+"\\root\\cimv2");
            ms.Options.EnablePrivileges = true;
            try
            {
                ms.Connect();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.ToString());
            }
            if (ms.IsConnected)
            {
                try
                {
                    ObjectQuery oq = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
                    ManagementObjectSearcher mos = new ManagementObjectSearcher(ms, oq);
                    ManagementObjectCollection moc = mos.Get();
                    foreach (ManagementObject mo in moc)
                    {
                        string[] ss = { "8", "4" };
                        mo.InvokeMethod("Win32Shutdown", ss);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        public static bool InsertAccessNickName(string nickname,int shopId)
        {
            bool ret =false;
            string strSql = "select cjNum from shopInfo where nickName='" + nickname + "'";
            object obj = DBHelper.GetScalar(strSql);//数据库中没有该"掌柜名"
            if (obj == null)
            {
                string insertSql = "insert into shopInfo values('" + shopId + "','" + nickname + "',0)";
               // list.Add(shopSearchStruct);
                ret=DBHelper.ExecuteCommand(insertSql);
            }
            else
            {   //update shopInfo set xx='5',set yy='6' where nick
                string updateSql = "update shopInfo set shopId='" + shopId + "',cjNum=" + (Convert.ToInt32(obj) + 1) + " where nickName='" + nickname + "'";
                ret=DBHelper.ExecuteCommand(updateSql);
            }
            return ret;
        }

        public static bool DeleteAccessNickname(string nickname)
        {
            bool ret = false;
            string strSql = "delete *from shopInfo where nickName='" + nickname + "'";
            ret=DBHelper.ExecuteCommand(strSql);
            return ret;
        }

        public static HtmlAgilityPack.HtmlDocument ParaseToHtml(string htmlStr)
        {
            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(htmlStr);
            return htmlDoc;
        }

        /// <summary>
        /// 判断循环中是否重启路由的条件
        /// </summary>
        /// <param name="dict">INI中设定的字典重启条件</param>
        /// <param name="htmlStrTitle">访问HttpRequest得到的HTML Title串</param>
        /// <returns>true：含有重启条件，false：不含有重启条件</returns>
        public static bool ExistDict(Dictionary<string, string> dict, string htmlStrTitle)
        {
            string str = htmlStrTitle.Split(',', '-', ':', '。')[0].Trim();
            foreach (KeyValuePair<string, string> item in dict)
            {
                if (item.Value.ToString().Contains(str))
                    return true;
            }
            return false;
        }
    }
}
